package cn.com.hbhgkj.webapp.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.google.code.kaptcha.Constants;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * Correctly report spring-security's AccessDeniedException thrown from within
 * Struts actions as 403 error. These exceptions can be fired in a call to the
 * service layer, for instance.
 * 
 * @author jgarcia
 */
public class CaptchaInterceptor implements Interceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String captcha = ServletActionContext.getRequest().getParameter(
				"captcha");

		Object storedCaptcha = ServletActionContext.getRequest()
				.getSession(false).getAttribute(Constants.KAPTCHA_SESSION_KEY);

		if (StringUtils.isEmpty(captcha) || !captcha.equals(storedCaptcha)) {
			if (invocation.getAction() instanceof ActionSupport) {
				ActionSupport as = (ActionSupport) invocation.getAction();
				as.addFieldError("captcha", as.getText("errors.captcha.invalid"));
				return Action.INPUT;
			}
		}
		return invocation.invoke();
	}

	/**
	 * This method currently does nothing.
	 */
	@Override
	public void destroy() {
	}

	/**
	 * This method currently does nothing.
	 */
	@Override
	public void init() {
	}
}
